package dao.impl;

import dao.MasterDao;
import entity.Master;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class MasterDaoImpl extends BaseDao implements MasterDao {

    @Override
    //登入
    public Master getMaster(String username, String password) throws Exception {
        connection = getConnection();
        String sql = "select * from master where username=? and userpassword=?";
        statement = connection.prepareStatement(sql);
        statement.setString(1, username);
        statement.setString(2, password);
        resultSet = statement.executeQuery();
        int userid = 0;
        Master master = null;
        if (resultSet.next()) {
            userid = resultSet.getInt("userid");
            master = new Master(userid, username, password);
        }
        close(resultSet, statement, connection);
        return master;
    }

    @Override
//注册
    public int getmaster(int id, String username, String password) throws Exception {
        connection = getConnection();
        String sql = "insert into master values (?,?,?)";
        statement = connection.prepareStatement(sql);
        statement.setInt(1, id);
        statement.setString(2, username);
        statement.setString(3, password);
        int i = statement.executeUpdate();
        close(resultSet, statement, connection);
        return i;
    }

    @Override
    //修改
    public int updeteMaster(String username, String password, String oldPassword) throws Exception {
        connection = getConnection();
        String sql = "update master set userpassword=? where username=?and userpassword=?";
        statement = connection.prepareStatement(sql);
        statement.setString(1, password);
        statement.setString(2, username);
        statement.setString(3, oldPassword);
        int i = statement.executeUpdate();
        close(resultSet, statement, connection);
        return i;
    }
//查询
    public List<Master> getlist() throws Exception {
        connection = getConnection();
        String sql = "select * from master";
        statement = connection.prepareStatement(sql);
        resultSet = statement.executeQuery();
        ArrayList<Master> list = new ArrayList<>();
        while (resultSet.next()) {
            int id = resultSet.getInt("userid");
            String username = resultSet.getString("username");
            String userpassword = resultSet.getString("userpassword");
            Master master = new Master(id, username, userpassword);
            list.add(master);

        }
        return list;
    }
}
